/*
 * DatabaseDemoHostApplication.java
 *
 * Copyright (c) 2008-2009 Sun Microsystems, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
package org.sunspotworld.demo;

import com.sun.spot.io.j2me.radiogram.*;

import java.io.IOException;
import javax.microedition.io.*;

/**
 * This application is the 'on Desktop' portion of the SendDataDemo. 
 * This host application collects sensor samples sent by the 'on SPOT'
 * portion running on neighboring SPOTs and graphs them in a window. 
 *   
 * @author Vipul Gupta
 * modified Ron Goldman
 */
public class SunSpotGloveHostTestGUI {
    // Broadcast port on which we listen for sensor samples

    private static final int HOST_PORT = 100;
    private static final int REFRESH_FREQUENCY = 10;  //Hz
    private static boolean CONNECT_ONCE = false;
    private RadiogramConnection conn;
    private Datagram dg;
    private DataWindow xplot,yplot;

    private void run() throws Exception {

        if (CONNECT_ONCE) {
            try {
                conn = (RadiogramConnection) Connector.open("radiogram://:" + HOST_PORT);
                dg = conn.newDatagram(conn.getMaximumLength());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        xplot = new DataWindow("Wykres przyspieszenia x", 1000 / REFRESH_FREQUENCY);
        yplot = new DataWindow("Wykres przyspieszenia y", 1000 / REFRESH_FREQUENCY);


        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                xplot.setVisible(true);
                yplot.setVisible(true);
            }
        });

        long time = System.currentTimeMillis();

        while (true) {

            time = System.currentTimeMillis();

            String rawData = readMessage();

            String data[] = rawData.split(";");
            double x = Double.parseDouble(data[0]);
            double y = Double.parseDouble(data[1]);
            double z = Double.parseDouble(data[2]);

            long sampleTime = System.currentTimeMillis();

            xplot.addData(sampleTime, x);
            yplot.addData(sampleTime, y);

            try {
                long czas = Math.max(0, 1000 / REFRESH_FREQUENCY - (System.currentTimeMillis() - time));
                Thread.sleep(czas);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    private String readMessage() {

        String result = null;

        try {
            if (!CONNECT_ONCE) {
                conn = (RadiogramConnection) Connector.open("radiogram://:" + HOST_PORT);
                dg = conn.newDatagram(conn.getMaximumLength());
            }

            try {
                conn.receive(dg);
                result = dg.readUTF();
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            if (!CONNECT_ONCE) {
                conn.close();
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return result;
    }

    /**
     * Start up the host application.
     *
     * @param args any command line arguments
     */
    public static void main(String[] args) throws Exception {

        SunSpotGloveHostTestGUI app = new SunSpotGloveHostTestGUI();
        //app.setup();
        app.run();
    }
}
